package foliotracker;

import java.net.MalformedURLException;
import java.net.URL;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class YahooStockPriceService implements IStockPriceService
{
	private static final String SERVICE_URL = "http://finance.yahoo.com/d/quotes.csv?f=%s&s=%s";
	
	public YahooStockPriceService()
	{
		System.setProperty("java.net.useSystemProxies", "true");
	}

	@Override
	public double getStockPrice(String symbol) throws UnknownStockSymbolException, StockPriceServiceException
	{
		String strPrice = getResponse("l1", symbol);
		
		if (strPrice.equals("0.00"))
		{
			//stock symbol not found
			throw new UnknownStockSymbolException(symbol);
		}
		else
		{
			return Double.valueOf(strPrice);
		}
	}
	
	@Override
	public String getStockName(String symbol) throws UnknownStockSymbolException, StockPriceServiceException
	{
		String strName = getResponse("n", symbol);
		
		if (strName.equals(String.format("\"%s\"", symbol)))
		{
			//if we just get the symbol name back, the symbol doesn't exist
			throw new UnknownStockSymbolException(symbol);
		}
		else
		{
			//strip the quotes
			return strName.substring(1, strName.length() - 2);
		}
	}
	
	private String getResponse(String format, String symbol) throws StockPriceServiceException
	{
		try
		{
			URL url = new URL(String.format(SERVICE_URL, format, symbol));
			BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
			return reader.readLine();
		}
		catch (MalformedURLException e)
		{
			throw new StockPriceServiceException("Malformed service URL.");
		} 
		catch (IOException e)
		{
			throw new StockPriceServiceException("Error reading from service URL.");
		}
	}
}
